package com.taocyb.framework.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpHeaders;

/**
 * Http与Servlet工具类。
 */
public class Servlets {
	/**
	 * 获取真实IP地址
	 */ 
	public static String getRemoteIp(HttpServletRequest request) {     
	      String ip = request.getHeader("x-forwarded-for");     
	      if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {     
	         ip = request.getHeader("Proxy-Client-IP");     
	     }     
	      if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {     
	         ip = request.getHeader("WL-Proxy-Client-IP");     
	      }     
	     if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {     
	          ip = request.getRemoteAddr();     
	     }     
	     return ip;     
	}
	
	/**
	 * 设置禁止客户端的缓存
	 */
	public static void setNoCacheHeader(HttpServletResponse response) {
		response.setDateHeader(HttpHeaders.EXPIRES, 1L);
		response.addHeader(HttpHeaders.PRAGMA, "no-cache");
		response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, max-age=0");
	}
	
	/**
	 * 根据cookie名字获取cookie对象 
	 */
	public static Cookie getCookie (HttpServletRequest request, String name){
		Cookie[] cookies = request.getCookies();
		if(null != cookies && cookies.length > 0){
			for(Cookie cookie : cookies){
			    if(cookie.getName().equals(name)){
			    	return cookie;
			    }
			}
		}
		
		return null;
	}
}